package com.capinfo.accumulation.web.controller.collection;

import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.CompanyAccountFund;
import com.capinfo.accumulation.parameter.collection.CompanyAccountFundParameter;
import com.capinfo.accumulation.parameter.collection.CompanyParameter;
import com.capinfo.accumulation.service.collection.CompanyAccountFundService;
import com.capinfo.accumulation.service.collection.CompanyService;
import com.capinfo.accumulation.service.collection.CompanyUtilService;
import com.capinfo.accumulation.web.Constants;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.commons.project.parameter.security.SystemResourceParameter;
import com.capinfo.commons.project.service.security.SystemUserService;
import com.capinfo.commons.project.utils.JsonUtils;
import com.capinfo.commons.project.web.controller.manage.region.RegionManageController;
import com.capinfo.framework.model.dictionary.Dictionary;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by cairunbin on 2017/10/24.
 */


@Controller
@RequestMapping("/business/collection/company_account_fund")
public class CompanyAccountFundController extends CommonsDataManageController<CompanyAccountFundParameter, CompanyAccountFund> {

    private static final Log logger = LogFactory.getLog(RegionManageController.class);
    @Autowired
    private CompanyAccountFundService companyAccountFundService;

    //审核操作
    @RequestMapping("/company_account_fund_audit.shtml")
    public void audit(NativeWebRequest request, CompanyAccountFundParameter parameter, OutputStream stream) throws UnsupportedEncodingException {
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        Boolean token = companyAccountFundService.audit(parameter);
        if (token) {
            JSONObject json = new JSONObject();
            json.put("id", parameter.getEntity().getId());
            json.put("result", true);
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } else {

            IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
        }
    }


    @RequestMapping("/is_exist.shtml")
    public void isExist(NativeWebRequest request, CompanyAccountFundParameter parameter, OutputStream stream) {
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        if (null == parameter.getEntity().getId()) {
            CompanyAccountFund companyAccountFund = companyAccountFundService.isExist(parameter);
            Map map = new HashMap<String, Object>();
            if (companyAccountFund == null) {
                map.put("result", false);
                map.put("flag","one");
                map.put("errMsg", "查无此公司");
            }else {
                if (companyAccountFund.getAccumulationFundAccountTypeId() == 87) {//公积金账户类型1.基本2.补充
                    if (companyAccountFund.getCompanyAccountStateId() == 1){//公积金账户状态1.为已注销
                        map.put("result", false);
                        map.put("flag","two");
                        map.put("errMsg", "单位基本公积金账户为注销，不可开设补充公积金账户");
                    }else{
                        map.put("result", true);
                        map.put("errMsg", "");
                        map.put("companyAccountFund_id",companyAccountFund.getId());
                        map.put("gbCompanyAccount",companyAccountFund.getCompany().getGbCompanyAccount());
                        map.put("gbCompanyName",companyAccountFund.getCompany().getGbCompanyName());
                        map.put("companyAddress",companyAccountFund.getCompany().getCompanyAddress());
                        map.put("gbCompanyPostCode",companyAccountFund.getCompany().getGbCompanyPostCode());
                        map.put("natureAccountId",companyAccountFund.getCompany().getNatureAccountId());
                        map.put("startPaymentDate",companyAccountFund.getStartPaymentDate());
                        map.put("contactName",companyAccountFund.getCompany().getContactName());
                        map.put("contactIdCardTypeId",companyAccountFund.getCompany().getContactIdCardTypeId());
                        map.put("contactIdCardNumber",companyAccountFund.getCompany().getContactIdCardNumber());
                        map.put("contactMobilePhone",companyAccountFund.getCompany().getContactMobilePhone());
                        map.put("companyId",companyAccountFund.getCompanyId());

                       /* System.out.println(companyAccountFund.getCompany().getGbCompanyName()+"------"+companyAccountFund.getCompany().getCompanyAddress());

                        map.put("companyAccountFund",companyAccountFund);*/

                       //JsonUtils.toJson4EntityByProperties():一个对象中需要传递什么属性到前台，就在后面填上什么属性，其余的自动替换为默认的
                      //JsonUtils.toJson4Entity():一个对象中需要剔除哪些属性，就填写哪些属性
                       /* map.put("companyAccountFund",JsonUtils.toJson4EntityByProperties(companyAccountFund,"gbCompanyName",
                                "gbCompanyAddress","gbCompanyPostCode","natureAccount","contactName",
                                "contactIdCardTypeId","contactIdCardNumber","contactMobilePhone","id"));*/
                    }
                }else{
                    map.put("result", false);
                    map.put("flag","three");
                    map.put("errMsg", "单位已开设补充公积金账户，不可重复开设");
                }
            }
            try {
                IOUtils.outputByStream(stream,JsonUtils.toGlobleJsonObject(map).toString().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LogUtils.debugException(logger, e);
            }
        }
    }

    @Override
    protected void saveOrUpdateAfterInvoke(NativeWebRequest request, CompanyAccountFundParameter parameter, CompanyAccountFund entity){
        WebRequestUtils.setContentType(request, "application/json;charset=UTF-8");

        Object nativeResponse = request.getNativeResponse();
        if( nativeResponse instanceof ServletResponse ) {

            HttpServletResponse response = (HttpServletResponse) nativeResponse;
            OutputStream stream = null;
            try {
                stream = response.getOutputStream();
                boolean token = entity == null ? false : true;
                if (token) {
                    JSONObject json = new JSONObject();
                    json.put("id", entity.getId());
                    json.put("result", "success");

                    IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
                } else {

                    IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public CommonsDataOperationService<CompanyAccountFund, CompanyAccountFundParameter> getCommonsDataOperationService() {

        return companyAccountFundService;
    }


    /*
    补充公积金search.jsp获取下拉表单的值以及默认时间
     */
    @RequestMapping({"/search.shtml"})
    public Map<String, Object> search(CompanyAccountFundParameter parameter) {

        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        Set<Dictionary> paymentSiteList = companyAccountFundService.getDictionariesBySortName("缴存网点");
        viewModel.put("paymentSiteList",paymentSiteList);

        //得到当前时间、一个月之前的时间,传至search.jsp页面
        Date endDate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(endDate);
        cal.add(Calendar.MONTH,-1);
        Date startDate = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(endDate)+"--------"+sdf.format(startDate));
        viewModel.put("endDate",sdf.format(endDate));
        viewModel.put("startDate",sdf.format(startDate));

        return viewModel;
    }

    /**
     * 字典项
     */

        protected Map<String, Object> formAfterInvoke(NativeWebRequest request, CompanyAccountFundParameter parameter, Map<String, Object> viewModel) {
        Set<Dictionary> natureAccountIdList = companyAccountFundService.getDictionariesBySortName("账户性质");
        viewModel.put("natureAccountIdList",natureAccountIdList);
        Set<Dictionary> depositRateMarkIdList = companyAccountFundService.getDictionariesBySortName("缴存率标志");
        viewModel.put("depositRateMarkIdList",depositRateMarkIdList);
        Set<Dictionary> companyPaymentRatioList = companyAccountFundService.getDictionariesBySortName("单位缴存比例");
        viewModel.put("companyPaymentRatioList",companyPaymentRatioList);
        Set<Dictionary> personPaymentRatioList = companyAccountFundService.getDictionariesBySortName("个人缴存比例");
        viewModel.put("personPaymentRatioList",personPaymentRatioList);
        Set<Dictionary> contactIdCardTypeIdList = companyAccountFundService.getDictionariesBySortName("证件类型");
        viewModel.put("contactIdCardTypeIdList",contactIdCardTypeIdList);
        return viewModel;
    }







}
